package com.pap.oauth.config.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 *  自定义一个 UserDetailsManager， 用来通过 username 获取 UserDetails 对象，
 *  防止在 security.oauth2 的处理逻辑中，找不到在 SecurityConfig 中定义的 用户信息，
 *  需要注意： 这里不仅仅要在 security 中进行用户定义，同时要在 oauth2 中进行用户定义。
 *
 *  @Deprecated 取消对 userDetailsService 方法的支持，而改为在 Spring Security 扩充登录方法的方式进行替换。
 */
@Deprecated
// @Service
public class PapUserDetailsService implements UserDetailsManager {

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // TODO 后续这里可以通过 DB 进行用户数据查询。
        String password;
        List<GrantedAuthority> auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER");
        if (username.equals("pap")) {
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_PAP");
            password = "pap";
        }
        else if (username.equals("alexgaoyh")){
            auth = AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ALEXGAOYH,ROLE_PAP");
            password = "alexgaoyh";
        }
        else{
            throw new UsernameNotFoundException("Username was not found. ");
        }
        return new org.springframework.security.core.userdetails.User(username, password, auth);
    }

    @Override
    public void createUser(UserDetails user) {// TODO Auto-generated method stub
    }

    @Override
    public void updateUser(UserDetails user) {// TODO Auto-generated method stub
    }

    @Override
    public void deleteUser(String username) {// TODO Auto-generated method stub
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        // TODO Auto-generated method stub
    }

    @Override
    public boolean userExists(String username) {
        // TODO Auto-generated method stub
        return false;
    }
}